
/*
********************************************************************************
Copyright (c) 2001 Center for Visual Science

Module Name: CVSElapsedTimer.cpp

Abstract: implement a Win32-oriented high frequency, high resolution timer

History
................................................................................
12/11/2001  rmu     created original
12/18/2001  rmu     added Reset()
********************************************************************************
*/
#include <windows.h>
#include "CVSElapsedTimer.h"

CVSElapsedTimer::CVSElapsedTimer()
{
	// Why are there two of these? Is this a mistake?
	QueryPerformanceFrequency ((LARGE_INTEGER *) &m_n64TimerFrequency);
	QueryPerformanceCounter ((LARGE_INTEGER *) &m_n64StartingTime);
	QueryPerformanceFrequency ((LARGE_INTEGER *) &m_n64TimerFrequency);
	QueryPerformanceCounter ((LARGE_INTEGER *) &m_n64StartingTime);
	// set max number of waiting cycles
	maxNumWaitCycles = 240*m_n64TimerFrequency; 
	// assuming 1 counter per loop, 
	// default limit on wait is about 240 sec (4 min)
}

CVSElapsedTimer::~CVSElapsedTimer()
{

}

void CVSElapsedTimer::PrintInfo(std::ostream & os)
{
	os << "Timer Frequency:    \t" << m_n64TimerFrequency << std::endl;
	os << "Starting Time:      \t" << m_n64StartingTime << std::endl;
	os << "Microsec conversion:\t" << 
		((double)1000000)/((double)m_n64TimerFrequency) << std::endl;
	os << "Max Wait Cycles:    \t" << maxNumWaitCycles << std::endl;
}


// ... Operations
CVSElapsedTimer::datatype CVSElapsedTimer::ElapsedTime (void)
{
	datatype now, elapsed;
	QueryPerformanceCounter ((LARGE_INTEGER*) &now);
	// ... Convert to microseconds.
	elapsed = (now - m_n64StartingTime) * 1000000 / m_n64TimerFrequency;
	return elapsed;
}


void CVSElapsedTimer::Reset (void)
{
	QueryPerformanceCounter ((LARGE_INTEGER *) &m_n64StartingTime);
}

bool CVSElapsedTimer::WaitMilliSec(double wait_time)
{
	datatype numcycles = 0;
	double waitstart;
	if(wait_time <= 0.0) return(true);
	waitstart = ElapsedTimeMilliSec();
	while(ElapsedTimeMilliSec() < (waitstart + wait_time)) 
	{ 
		if(numcycles++ > maxNumWaitCycles) return(false);
	}
	//cout << "waited for " << numcycles << " cycles" << endl;
	return(true);
}

